package com.ydw.blog.web.admin;

import com.ydw.blog.entity.Type;
import com.ydw.blog.service.TypeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.bind.BindResult;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.validation.Valid;

@Controller
@RequestMapping("/admin")
@Slf4j
public class TypeController {

    @Autowired
    private TypeService typeService;

    @RequestMapping("/types")
    public String type(@PageableDefault(size = 5,sort = {"id"},direction = Sort.Direction.DESC) Pageable pageable, Model model){

        model.addAttribute("page",typeService.ListType(pageable));

        return "admin/types";
    }

    @PostMapping("/types")
    public String postTypes(@Valid Type type, BindResult result, RedirectAttributes redirect){
        Type t = typeService.saveType(type);
        log.info(t.toString());
        if (t != null){
            redirect.addFlashAttribute("message", "添加成功");
        }else{
            redirect.addFlashAttribute("message", "添加失败");
        }
        return "redirect:/admin/types";
    }
}
